package com.guojiang.guopicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.guojiang.guopicturebackend.exception.ErrorCode;
import com.guojiang.guopicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 图片文件上传
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "图片文件不能为空");
        // 1. 校验图片大小
        long pictureSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(pictureSize > 8 * ONE_M, ErrorCode.PARAMS_ERROR, "图片大小不能超过 8MB");
        // 2. 校验文件后缀
        // 获取文件后缀
        String pictureSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 定义允许上传的文件后缀列表
        final List<String> ALLOW_SUFFIX_LIST = Arrays.asList("jpeg", "png", "jpg", "webp", "bmp");
        ThrowUtils.throwIf(!ALLOW_SUFFIX_LIST.contains(pictureSuffix)
                , ErrorCode.PARAMS_ERROR, "不支持上传该类型的图片");
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception{
        MultipartFile multipartFile = (MultipartFile) inputSource;
        // multipartFile 传输到 file
        multipartFile.transferTo(file);
    }
}
